<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

JFX::checkAdminPermsRedirect('core', 'perm_save_templates');

// first lets save our blocks
$block = json_decode($_POST['element']);

//var_dump($block);

JFX_SaveBlockTemplate_SaveTemplate($block);

// now update the block to be a template
$id = $DB->escape($block->id);

$DB->update($CONFIG->dbprefix.'blocks', array('is_template' => 1, 'workspace_id'=>1), "id = '{$id}'");

if($DB->oneValue($CONFIG->dbprefix.'blocks', 'is_template', "id = '{$id}'")==1){
    $res->status = 'OK';
}else{
    $res->status = 'FAIL';
}

echo json_encode($res);
exit;
















function JFX_SaveBlockTemplate_SaveTemplate($element){
    $DB = JFX::registry('db');
    $CONFIG = JFX::registry('config');
    $elements = array();
    $parentId = $element->id;
    if($parentId == 'page_'.$element->pageid) $isPageParent = true;
    else $isPageParent = false;
    //$DB->debug(true);
    //$DB->showErrors(true);
    foreach($element->elements as $k=>$v){
        $elementId = $DB->escape($v->id);
        $bData = $v->details;
        $block = new JFX_Block;
        if(!$block->loadById($v->id)){
            // create a new block
            $block = JFX_Block::newModuleBlock($bData->module_key);
        };
        if(count($v->elements)>0){
            $block->elements = JFX_SaveBlockTemplate_SaveTemplate($v);
        };
        if(false===$block->setDetails($bData)) die('error setting details');
        $block->save();
        $elements[] = $block;
    }
    //$DB->showErrors(false);
    return $elements;
    //$DB->debug(false);

}
